package leraning.httpUrlConnection;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnection1 {
	public static void main(String[] args) {
		URL url = null;
		File file=new File("img/img.jpg");
		try {
			url = new URL(
					"http://pic3.zhongsou.com/image/3802ea1855025bc5ac5.jpg");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				System.out.println("request successfully");
				InputStream is=conn.getInputStream();
				FileOutputStream os=new FileOutputStream(file);
				int len=0;
				byte[] bb=new byte[1024];
				while((len=is.read(bb))!=-1){
					os.write(bb, 0, len);
					os.flush();
				}
				System.out.println("download finished");
				is.close();
				os.close();
				conn.disconnect();
			} else
				System.out.println("request error");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
